package com.ihrm.company.service;

import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.dao.DepartmentDao;
import com.ihrm.domain.company.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;

/**
 * @author chahua
 * @date 2022/3/27 11:20
 **/
@Service
public class DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 新增部门
     * @param department 数据
     */
    public void add(Department department){
        String id = idWorker.nextId() + "";
        department.setId(id);
        departmentDao.save(department);
    }

    /**
     * 更新部门
     * @param department 数据
     */
    public void update(Department department){
        // 根据id查询部门
        Department dept = departmentDao.findById(department.getId()).get();
        dept.setName(department.getName());
        dept.setCode(department.getCode());
        department.setIntroduce(department.getIntroduce());
        departmentDao.save(dept);
    }

    /**
     * 根据id删除部门
     * @param id 部门id
     */
    public void deleteById(String id){
        departmentDao.deleteById(id);
    }

    /**
     * 根据id查询部门
     * @param id 部门id
     * @return Department
     */
    public Department findById(String id){
        return departmentDao.findById(id).get();
    }

    /**
     * 根据企业id查询该企业下的所有部门
     * @param companyId 企业id
     * @return
     */
    public List<Department> findAll(String companyId){

        /**
         * 根据条件查询获取全部数据；
         */
        List<Department> departmentList = departmentDao.findAll(new Specification<Department>() {
            /**
             * 查询条件
             * @param root 查询的根对象（查询的任何属性都可以从根对象中获取）
             * @param criteriaQuery 顶层的查询对象，一般用不到
             * @param criteriaBuilder 查询的构造器，封装了很多的查询条件
             * @return Predicate
             */
            @Override
            public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                // 1. 获取比较的属性，compnayId是Department实体类中的属性companyId
                Path<Object> id = root.get("companyId");

                // 2. 查询条件：数据库中的id和查询的companyId是否相等
                // 参数1：期望的数据库中的id
                // 参数2：要查询的companId
                return criteriaBuilder.equal(id, companyId);
            }
        });
        return departmentList;
    }
}
